package handler

import (
	"github.com/gorilla/websocket"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"yunzhan/log-server/internal/logic"
	"yunzhan/log-server/internal/svc"
	"yunzhan/log-server/internal/types"
)

var upGrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func LogHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.WebSocketRequest
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		conn, err := upGrader.Upgrade(w, r, nil)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}
		defer conn.Close()

		l := logic.NewLogLogic(r.Context(), svcCtx)
		if err := l.Log(&req, conn); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		}
	}
}
